package cn.caijiapeng.spt.service;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Page;

import cn.caijiapeng.spt.bean.Operate;
import cn.caijiapeng.spt.kit.LocationKit;
import cn.caijiapeng.spt.model.SysAccess;
import cn.caijiapeng.spt.model.SysLoginLog;

public class SysLoginLogService {
	public final static SysLoginLogService srv = new SysLoginLogService();
	private final SysLoginLog dao = new SysLoginLog();
	
	public Operate<SysLoginLog> create(SysAccess access, String ip, String userAgent){
		SysLoginLog log = new SysLoginLog();
		log.set("user_id", access.get("user_id"));
		log.set("username", access.get("username"));
		log.set("ip", ip);
		Operate<JSONObject> ipLocation = LocationKit.getLocationByIp(ip);
		if(ipLocation.isOk()) {
			JSONObject data = ipLocation.get().getJSONObject("data");
			String location = data.getString("region") + "-" + data.getString("city");
			log.set("ip_location", location);
		}
		
		log.set("useragent", userAgent);
		if(log.save()) {
			return Operate.ok(log);
		}
		return Operate.fail();
	}
	
	public Page<SysLoginLog> getPage(Integer pageNumber, Integer pageSize){
		return dao.paginate(pageNumber, pageSize, "select * ", "from " + dao.getTableName() + " order by id desc");
	}
}
